#include "SoftUart.h"


// #pragma GCC push_options
// #pragma GCC optimize ("Os")

static void BitTime(void)
{
	volatile int32_t i ;
#if   ( MAIN_OSC == 36000000 )
    i = 12; // 9600 bsp   104us 
#elif ( MAIN_OSC == 12000000 ) // 此时1 -> 22us
    // i = 36; // 1200 bsp    839us
    i = 1 ; i=2; // 9600 bsp
#elif ( MAIN_OSC == 8000000 ) // 通过 多条指令组合得到延时  109us 4.8%的误差
    i = 1 ; // 9600 bsp 
    i = 2 ; 
    i = 3 ;
    i = 4 ;
    return ;
#elif   ( MAIN_OSC == 50000000 )
    i = 18; // 105us   9600 bsp
#elif   ( MAIN_OSC == 100000000 )
    i = 37; // 103us   9600 bsp
#elif   ( MAIN_OSC == 148148169 )
    i = 56; // 103.7us   9600 bsp
#elif   ( MAIN_OSC == 150000000 )
    i = 57; // 104us   9600 bsp
#else 
    #error this MAIN_OSC is not support! 
#endif 
	while(--i);
}

void TxSend(volatile uint8_t dat)
{
    uint8_t fag = 0x02 ;

    P_TXD = ((fag>>0) & 0x01) ? 1:0; BitTime(); // 起始位 

    P_TXD = ((dat>>0) & 0x01) ? 1:0; BitTime(); 
    P_TXD = ((dat>>1) & 0x01) ? 1:0; BitTime(); 
    P_TXD = ((dat>>2) & 0x01) ? 1:0; BitTime(); 
    P_TXD = ((dat>>3) & 0x01) ? 1:0; BitTime(); 
    P_TXD = ((dat>>4) & 0x01) ? 1:0; BitTime(); 
    P_TXD = ((dat>>5) & 0x01) ? 1:0; BitTime(); 
    P_TXD = ((dat>>6) & 0x01) ? 1:0; BitTime(); 
    P_TXD = ((dat>>7) & 0x01) ? 1:0; BitTime();  

    P_TXD = ((fag>>1) & 0x01) ? 1:0; BitTime(); // 停止位
    BitTime();
}

void TxStr(uint8_t *c)
{
	uint8_t i =0;
	while(1)
	{
		if(c[i]=='\0')break;
		TxSend(c[i]) ;
		i++;
	}

}

void TxInt16(int16_t x)
{
    volatile uint8_t i;
    uint8_t t_buf[10] = {0, 0, 0, 0, 0};
    uint8_t flag = 0;
    if (x == 0)
    {
        TxSend('0');
        return;
    }
    if (x < 0)
    {
        TxSend('-');
        x = -x;
    }
    for (i = 0; i < 5; i++)
    {
        t_buf[4 - i] = x % 10;
        x = x / 10;
    }
    for (i = 0; i < 5; i++)
    {
        if (!flag && t_buf[i] != 0)
        {
            flag = 1;
            TxSend('0' + t_buf[i]);
        }
        else if (flag)
        {
            TxSend('0' + t_buf[i]);
        }
    }
}

// #pragma GCC pop_options  // 结束不优化的代码